<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.site_delete" @click="handleDelete">删 除 </el-button>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/admin/site';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        labelWidth: 180,
        column: [
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '代码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '站点类型',
            prop: 'siteType',
            type: 'select',
            search: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=site_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择站点类型',
                trigger: 'blur'
              }
            ],
            control: (val) => {
              if (val === 'WAREHOUSE') {
                this.form.isWarehouse = true;
                return {
                  fifoRequired: {
                    display: true
                  },
                  isLotRequired: {
                    display: true
                  },
                  sequenceFormatName: {
                    display: true
                  },
                  partCategories: {
                    display: true
                  }
                };
              } else {
                this.form.isWarehouse = false;
                return {
                  fifoRequired: {
                    display: false
                  },
                  isLotRequired: {
                    display: false
                  },
                  sequenceFormatName: {
                    display: false
                  },
                  partCategories: {
                    display: false
                  }
                };
              }
            }
          },
          {
            label: '子类型',
            prop: 'subType',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入子类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '描述',
            prop: 'description',
            rules: [
              {
                required: true,
                message: '请输入描述',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '负责人',
            prop: 'principalName',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入负责人',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal();
            }
          },
          {
            label: '联系方式',
            prop: 'contacts',
            rules: [
              {
                required: true,
                message: '请输入联系方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '边端唯一标识',
            prop: 'accessCode',
            rules: [
              {
                required: true,
                message: '请输入边端唯一标识',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '边端token',
            prop: 'accessToken',
            rules: [
              {
                required: true,
                message: '请输入边端token',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '是不是仓库',
            prop: 'isWarehouse',
            type: 'switch',
            value: false,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择是不是仓库',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '是否管理先进先出',
            prop: 'fifoRequired',
            type: 'switch',
            display: true,
            value: false,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '是否管理批次',
            prop: 'isLotRequired',
            type: 'switch',
            display: true,
            value: false,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '批次规则',
            prop: 'sequenceFormatName',
            type: 'search',
            disabled: true,
            display: true,
            rules: [
              {
                required: true,
                message: '请选择批次规则',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openSerialNumberCommonModal();
            }
          },
          {
            label: '该区域可存储物料类别',
            prop: 'partCategories',
            display: true,
            rules: [
              {
                required: true,
                message: '请输入该区域可存储物料类别',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '通知',
            prop: 'latestNotice',
            rules: [
              {
                required: true,
                message: '请输入通知',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '地址',
            prop: 'locationName',
            type: 'search',
            disabled: true,
            bind: 'location.name',
            rules: [
              {
                required: true,
                message: '请选择地址',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLocationCommonModal();
            }
          },
          {
            label: '组织',
            prop: 'orgId',
            type: 'select',
            dicUrl: '/api/mes-admin/organization/lazy-list',
            props: {
              label: 'name',
              value: 'id'
            },
            rules: [
              {
                required: true,
                message: '请输入组织',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      data: [],
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(),
      modalName: ''
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.site_add, false),
        viewBtn: this.vaildData(this.permission.site_view, false),
        delBtn: this.vaildData(this.permission.site_delete, false),
        editBtn: this.vaildData(this.permission.site_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      row.extFields = null;
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 打开用户选择模态框
     */
    openUserCommonModal() {
      this.modalName = 'userModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择用户（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '登录账号',
            prop: 'account',
            search: true,
            display: false
          },
          {
            label: '所属租户',
            prop: 'tenantName',
            slot: true,
            display: false
          },
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            display: false
          },
          {
            label: '所属角色',
            prop: 'roleName',
            slot: true,
            display: false
          },
          {
            label: '所属部门',
            prop: 'deptName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            prop: 'userTypeName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=user_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dataType: 'number',
            search: true,
            hide: true,
            display: false,
            prop: 'userType',
            rules: [
              {
                required: true,
                message: '请选择用户平台',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    /**
     * 打开序列号规则配置模态框
     */
    openSerialNumberCommonModal() {
      this.modalName = 'serialNumberModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '规则名称',
            prop: 'name'
          },
          {
            label: '规则编码',
            prop: 'code'
          },
          {
            label: '规则类型',
            prop: 'type',
            type: 'select',
            dicData: [
              {
                label: '生产',
                value: 'PRODUCT'
              },
              {
                label: '仓库',
                value: 'WAREHOUSE'
              },
              {
                label: '品质',
                value: 'QUALITY'
              }
            ]
          },
          {
            label: '进制字符',
            prop: 'hexString'
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo'
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNo'
          },
          {
            label: '前缀字符',
            prop: 'prefix'
          },
          {
            label: '后缀字符',
            prop: 'suffix'
          },
          {
            label: '序列号规则',
            prop: 'sequencenoformat'
          },
          {
            label: '规则位数',
            prop: 'charactersCount'
          },
          {
            label: '清零类型',
            prop: 'regressionType',
            type: 'select',
            dicData: [
              {
                label: '不清零',
                value: 'null'
              },
              {
                label: '年',
                value: 'yearType'
              },
              {
                label: '月',
                value: 'monthType'
              },
              {
                label: '周',
                value: 'weekType'
              },
              {
                label: '日',
                value: 'dayType'
              }
            ]
          },
          {
            label: '增量',
            prop: 'incrementQty'
          },
          {
            label: '分组规则',
            prop: 'groupingRule'
          },
          {
            label: '过滤字符',
            prop: 'filterChar'
          },
          {
            label: '序列号样例',
            // 当前规则生成的一个样例序列号
            prop: 'sequenceSample'
          },
          {
            label: '是否包含流水号',
            prop: 'containsSequenceNo',
            type: 'switch', //开关的类型
            align: 'center',
            width: 100,
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ],
            value: 0
          },
          {
            label: '分隔符',
            // 每个占位符之间的分隔符，用于识别外来编码每个部分的值，比如‘；’，‘/’等，如果需要用于识别条码，必须要配置分隔符。
            prop: 'delimiter'
          },
          {
            label: '是否同时用于识别条码',
            // 每位占位符都代表着一定的业务意义，解析出来导入系统。比如约定WO代表工单号。
            prop: 'isIdentifyAlso',
            type: 'switch', //开关的类型
            align: 'center',
            width: 100,
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ],
            value: 0
          },
          {
            label: '是否需要占位符替换',
            // 如果是，需要在mes_sequence_holder_replacement增加规则。
            prop: 'requirePlaceholderReplacement',
            type: 'switch', //开关的类型
            align: 'center',
            width: 100,
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ],
            value: 0
          }
        ]
      };
    },
    /**
     * 打开地址选择模态框
     */
    openLocationCommonModal() {
      this.modalName = 'locationModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择位置（双击进行选择）',
        url: '/api/mes-admin/location/page?status=0',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '地址名称',
            prop: 'name'
          },
          {
            label: '国家',
            prop: 'country'
          },
          {
            label: '省份',
            prop: 'province'
          },
          {
            label: '城市',
            prop: 'city'
          },
          {
            label: '详细地址1',
            prop: 'location1'
          },
          {
            label: '详细地址2',
            prop: 'location2'
          },
          {
            label: '详细地址3',
            prop: 'location3'
          },
          {
            label: '详细地址4',
            prop: 'location4'
          },
          {
            label: '邮编',
            prop: 'postCode'
          },
          {
            label: '经度',
            prop: 'latitude'
          },
          {
            label: '纬度',
            prop: 'longitude'
          }
        ]
      };
    },
    /**
     * 选择模态框行数据
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'userModal') {
        this.form.principal = rowData.id;
        this.form.principalName = rowData.name;
      } else if (this.modalName === 'serialNumberModal') {
        this.form.serialNumberId = rowData.id;
        this.form.sequenceFormatName = rowData.name;
      } else if (this.modalName === 'locationModal') {
        this.form.locationId = rowData.id;
        this.form.locationName = rowData.name;
      }
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style></style>
